package com.wyzy.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wyzy.captcha.Configuration.CaptchaConfig;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaConfig captchaConfig;
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaConfig.getWidth(), captchaConfig.getHeight());
        response.setContentType("image/jpeg");
        response.setHeader("Pragma","No-cache");
        lineCaptcha.write(response.getOutputStream());
        session.setAttribute(captchaConfig.getSession().getCode(),lineCaptcha.getCode());
        session.setAttribute(captchaConfig.getSession().getDate(),new Date());
        System.out.println("生成的验证码是：" + lineCaptcha.getCode());
        response.getOutputStream().close();
    }

    private final static long VALID_MILLIS_TIME = 60 * 1000;
    @RequestMapping("/check")
    public boolean checkCaptcha(String captcha, HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String savedCaptcha = (String)session.getAttribute(captchaConfig.getSession().getCode());
        Date sessionDate = (Date)session.getAttribute(captchaConfig.getSession().getDate());
        if(captcha.equalsIgnoreCase(savedCaptcha)){
            if(sessionDate == null || System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME){
                return true;
            }
            return false;
        }
        return false;
    }
}
